#include "server.h"
#include "log.h"
#include "proxy_message.h"
#include "invoke_stub.h"
#include "util.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>


static thread_context * global_thd_cxt;

static int init_thread_conext() {
	global_thd_cxt = NULL;
	return 0;
}

static int fini_thread_context() {
	thread_context *current, *tmp;
	HASH_ITER(hh, global_thd_cxt, current, tmp) {
		HASH_DEL(global_thd_cxt, current);
		pthread_cancel(current->thread_id);  //stop thread
		free(current);
	}
	return 0;
}

static thread_context * find_thread_context(int fd) {
	thread_context * item = NULL;
	HASH_FIND_INT(global_thd_cxt, &fd, item);
	return item;
}

static int insert_thread_context(int fd, pthread_t thd_id) {
	thread_context * item = find_thread_context(fd);
	if (item) {
		return -1;
	}
	item = malloc(sizeof(thread_context));
	item->conn_fd = fd;
	item->thread_id = thd_id;
	HASH_ADD_INT(global_thd_cxt, conn_fd, item);
	return 0;
}

/**
 * [worker_thread_func description]
 * @param context [description]
 */
static void * worker_thread_func(void * context) {
	int conn_fd = *((int *)context);
	INFO("worker thread startup for conn_fd : %d", conn_fd);
	while (1) {
		struct timeval start_time, end_time2;
		SoaProxyRequest * req_msg = NULL;
		if (proxy_request_receive(conn_fd, &req_msg)) {
			ERROR("proxy_request_receive failed : %d, %s", conn_fd, strerror(errno));
			break;
		}
		DEBUG("receive proxy request message : %d", conn_fd);
		//TODO : transfer request to backend server
		int success = 1;
		get_now_time(&start_time);
		char * resp_buffer;
		size_t resp_buf_len;
		int ret = invoke_service(req_msg->group_name, req_msg->service_name, req_msg->service_version, req_msg->request.data, req_msg->request.len, &resp_buffer, &resp_buf_len);
		if (!ret) {
			//TODO : transfer response from backend server
			DEBUG("invoke_service success : %d", conn_fd);
			if (proxy_response_send(conn_fd, 0, resp_buffer, resp_buf_len)) {
				ERROR("proxy_response_send failed : %d, %s", conn_fd, strerror(errno));
				success = 0;
			}
			DEBUG("send proxy response message : %d", conn_fd);
			free(resp_buffer);
		} else {
			DEBUG("invoke_service failed : %d", conn_fd);
			if (proxy_response_send(conn_fd, 1, NULL, 0)) {
				ERROR("proxy_response_send failed : %d, %s", conn_fd, strerror(errno));
				success = 0;
			}
			DEBUG("send proxy response message : %d", conn_fd);
		}
		proxy_request_decode_clean(req_msg);
		get_now_time(&end_time2);
		unsigned int cost2 = get_time_difference(&start_time, &end_time2);
		INFO("%d total cost time (ms) : %d", conn_fd, cost2);
		if (!success) {
			break;
		}
	}
	close(conn_fd);  //close conn fd
	INFO("worker thread shutdown for conn_fd : %d", conn_fd);
}


int tcp_socket_server_startup(const char * host, int port) {
	int listen_fd, conn_fd;
	struct sockaddr_in serv_addr, remote;
	socklen_t sin_size = sizeof(struct sockaddr_in);

	//
	listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == listen_fd) {
		ERROR("socket error : %s", strerror(errno) );
		return -1;
	}

	int opt = SO_REUSEADDR;
	setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	//serv_addr.sin_addr.s_addr = INADDR_ANY;
	inet_pton(AF_INET, host, &serv_addr.sin_addr);
	bzero(&serv_addr.sin_zero, 8);

	if (-1 == bind(listen_fd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr))) {
		ERROR("bind error : %s", strerror(errno) );
		return -1;
	}

	if (-1 == listen(listen_fd, 5)) {
		ERROR("listen error : %s", strerror(errno) );
		return -1;
	}

	INFO("begin to accept connections...");
	while (1) {
		conn_fd = accept(listen_fd, (struct sockaddr *)&remote, &sin_size);
		if (conn_fd == -1) {
			ERROR("accept error : %s", strerror(errno) );
			continue;
		}
		INFO("accept conn_fd : %d", conn_fd);
		//create new thread to handle this conn_fd, when conn_fd close, so exit the thread
		pthread_t tid;
		int ret = pthread_create(&tid, NULL, (void*)worker_thread_func, (void*)&conn_fd);
		if (ret) {
			ERROR("pthread_create error : %s", strerror(errno) );
			continue;
		}
	}

	return 0;
}


int unix_socket_server_startup(const char * unix_sock_path) {
	int listen_fd, conn_fd;
	struct sockaddr_un local, remote;
	int sin_size = sizeof(struct sockaddr_un);

	//
	listen_fd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (-1 == listen_fd) {
		ERROR("socket error : %s", strerror(errno) );
		return -1;
	}

	int opt = SO_REUSEADDR;
	setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	local.sun_family = AF_UNIX;  /* local is declared before socket() ^ */
	strcpy(local.sun_path, unix_sock_path);
	//Notice that we called unlink() before bind() to remove the socket if it already exists.
	//You will get an EINVAL error if the file is already there
	unlink(local.sun_path);

	if (-1 == bind(listen_fd, (struct sockaddr *)&local, strlen(local.sun_path) + sizeof(local.sun_family))) {
		ERROR("bind error : %s", strerror(errno) );
		return -1;
	}

	if (-1 == listen(listen_fd, 5)) {
		ERROR("listen error : %s", strerror(errno) );
		return -1;
	}

	INFO("begin to accept connections...");
	while (1) {
		conn_fd = accept(listen_fd, (struct sockaddr *)&remote, &sin_size);
		if (conn_fd == -1) {
			ERROR("accept error : %s", strerror(errno) );
			continue;
		}
		INFO("accept conn_fd : %d", conn_fd);
		//create new thread to handle this conn_fd, when conn_fd close, so exit the thread
		pthread_t tid;
		int ret = pthread_create(&tid, NULL, (void*)worker_thread_func, (void*)&conn_fd);
		if (ret) {
			ERROR("pthread_create error : %s", strerror(errno) );
			continue;
		}
	}

	return 0;
}


/**
 * [server_startup description]
 * @param  unix_sock_path [description]
 * @return                [description]
 */
int server_startup(const char * unix_sock_path) {
	init_thread_conext();
	char ip_buf[20];
	int port;
	if (parse_addr(unix_sock_path, ip_buf, 20, &port) == 0) {
		tcp_socket_server_startup(ip_buf, port);
	} else {
		unix_socket_server_startup(unix_sock_path);
	}
	return 0;
}

